﻿requirejs.config({
    baseUrl: "js/",
    paths: {
        "jquery": ["/common/vendor/jquery-2.1.4/jquery-2.1.4.min"],
        "base": ["/common/scripts/base"],
        "ajax": ["/common/scripts/ajax"],
        "local": "/common/scripts/local",
        "underscore": ["/common/vendor/underscore-1.8.3/underscore.min"],
        "dataHandling": "data-handling",
        "swiper": ["/common/vendor/swiper-4.5/swiper.min"]
    },
    shim: {
        'underscore': {
            deps: ['dataHandling'],
            exprots: "_"
        }
    }
});

require(["jquery", "base", "ajax","local","dataHandling","underscore","swiper"], function($, base, ajax,local,dataHandling,_,swiper) {
    "use strict";
    var source = "", //系统源 150001 普通 150002 信用  150003 限售股 150000 全账户
        currency = "", //币种 401156 人民币 401344 港元 401840 美元
        account = "",//强账户
        startDate = base.getUrlParameter('startDate') || '',//开始时间
        endDate = base.getUrlParameter('endDate') || '',//结束时间
        dateType = base.getUrlParameter('dateType') || '',//日期类型
        pageSize = 50,//每页显示条数
        page = 1,//当前页,默认为1
        dataEnd = false,//上拉数据是否结束
        isRefresh = false;//上拉加载时,是否正在刷新数据
    var income = {
        /**
         * [init 初始化]
         * @return {[type]} [description]
         */
        init:function(){
            TalkingData.onHTSCEvent("page","leaf304", "持仓股综合分析_收益分析", "", "");
            this.swiper();
            this.bindEvent();
            //读取local的系统源,币种
            var _this = this;
            local.read({
                P_ACCOUNT:"",//强账户
                P_SOURCE: "",//系统源
                P_CURRENCYTYPE: ""//币种
            }, function(obj){
                base.log(obj.P_ACCOUNT);
                base.log(obj.P_SOURCE);
                base.log(obj.P_CURRENCYTYPE);
                account = obj.P_ACCOUNT;
                source = obj.P_SOURCE;
                currency = obj.P_CURRENCYTYPE;
                _this.getData();
            });
            this.pageEvent();
        },
        /**
         * [getData 获取所有持仓股盈亏分析数据]
         * @return {[type]} [description]
         */
        getData:function(){
            var self = this,
                url = "/reqxml?action=27401&path=/account/hold_analysis/income_explain",
                params = {
                    clientNo:account,
                    token:"($Token)",
                    source:source,//来源
                    currency:currency,//币种
                    startDate:startDate,
                    endDate:endDate,
                    dateType:dateType,
                    pageSize:pageSize,
                    page:page
                };
                base.log("page:"+page);
            ajax.run(url,params, function(data) {
                if(data && data.BINDATA){
                    var obj = JSON.parse(data.BINDATA),
                        code = obj.code,
                        msg = obj.msg;
                    if (code === "0") {
                        isRefresh = false;
                        self.parseData(obj.data);
                        // alert("成功！");
                    } else {
                        msg = msg && msg != '' ? msg : "接口返回错误"
                        alert(msg);
                    }
                }else{
                    alert("接口返回错误");
                }
            }, function(obj) {
                var msg = obj.ERRORMESSAGE && obj.ERRORMESSAGE != '' ? obj.ERRORMESSAGE : "网络错误";
                alert(msg);
            });
        },
        /**
         * [parseData 解析接口返回数据]
         * @param  {[type]} 接口返回数据 [description]
         * @return {[type]}      [description]
         */
        parseData:function(data){
            var self = this;
            //列表数据
            base.log("data.list.length:"+data.list.length);
            if(data && data.list && data.list.length != 0){
                self.renderHtml(data.list);
            }
            if(data && data.list && data.list.length == pageSize){
                $(".more").show();
            }else{
                dataEnd = true;//数据结束，下拉不再刷新数据
                var obj = document.getElementById("more");
                obj.innerHTML = "没有更多数据了";
                //判断小于一屏的高度就不展示
                var time = setTimeout(function() {
                    var bodyHeight = window.innerHeight,
                        useHeight = $("body").height() - $("footer").innerHeight();
                        base.log("屏幕高度:"+bodyHeight);
                        base.log("useHeight:"+useHeight);
                    if (bodyHeight > useHeight) {
                        $(".more").hide();
                    }else{
                        $(".more").show();
                    }
                }, 300);
            }
        },
        /**
         * [renderHtml 渲染页面]
         * @param  {[type]} 交易列表 [description]
         * @return {[type]}       [description]
         */
        renderHtml:function(list){
            var name_html = "",
                income_html = "",
                days_html = "";
            _.each(list,function(item){
                var money_html = '';
                if(item.money.indexOf("-")!=-1){
                    money_html = '<div class="value"><span class="loss">'+item.money+'</span></div>'
                }else{
                    money_html = '<div class="value"><span class="profit">'+item.money+'</span></div>'
                }
                //融字小图标
                var fuse_html = '';
                if(dataHandling.getFuse(item.source)){
                    fuse_html = '<span class="fuse"></span>'
                }

                var font13 = item.stockName.length>7?'font13':'';
                    name_html += '<li class="item" data-url="stockDetail" data-stockName='+item.stockName+' data-stockCode='+item.stockCode+ ' data-marketCode='+item.marketCode+ ' data-source='+item.source + '>'+
                                    '<div class="info">'+'<font class="'+ font13+'">'+item.stockName+'</font>' +
                                        '<div class="code">'+item.stockCode+ fuse_html +'</div>'+
                                    '</div>'+
                                 '</li>',

                    income_html += '<li class="item" data-url="stockDetail" data-stockName='+item.stockName+' data-stockCode='+item.stockCode+ ' data-marketCode='+item.marketCode+ ' data-source='+item.source + '>'+
                                      '<div class="value">'+item.incomePercent+'</div>'+
                                      money_html +
                                  '</li>',

                    days_html += '<li class="item" data-url="stockDetail" data-stockName='+item.stockName+' data-stockCode='+item.stockCode+ ' data-marketCode='+item.marketCode+ ' data-source='+item.source + '>'+
                                    '<div class="value">'+item.days+'</div>'+
                                    '<div class="value">'+item.tradeNum+'</div>'+
                                '</li>';
            });
            $(".income-analysis .detail .left").append(name_html);
            $(".income-analysis .detail .right .swiper-wrapper .info.first").append(income_html);
            $(".income-analysis .detail .right .swiper-wrapper .info.second").append(days_html);
            $(".footer").removeClass("hidden");
            
        },
        swiper:function(){
            this.swiper = new Swiper('.swiper-container',{
                 resistanceRatio:0,
                 onReachBeginning: function(swiper){
                      $(".switch-more").show();
                    },
                 onReachEnd: function(swiper){
                      $(".switch-more").hide();
                    }
            });      
        },
        /**
         * [bindEvent 页面事件绑定]
         * @return {[type]} [description]
         */
        bindEvent: function() {
            //链接跳转
            $(".detail").off("click").on("click","[data-url]",function(){
                var $this = $(this),
                    stockName = $this.attr("data-stockName"),
                    stockCode = $this.attr("data-stockCode"),
                    marketCode = $this.attr("data-marketCode"),
                    source = $this.attr("data-source"),
                    url = 'http://action:10061/?shownavigationbar=1&&type=9&&topcolor=F64843&&fullscreen=1&&url=/zlcftajax/information/position/stockDetail.htm?isFouse=' + dataHandling.getFuse(source) + '&source='+ source +'&currency='+ currency +'&startDate=' + startDate + '&endDate=' + endDate + '&stockName=' + encodeURIComponent(stockName) + '&stockCode=' + stockCode + '&marketCode=' + marketCode;
                    base.href(url);
                    var sourceDis = source == "150002" ? "融资融券" : "普通交易";
                    //alert("sourceDis:"+sourceDis);
                    TalkingData.onHTSCEvent("click","leaf304", "持仓股综合分析_收益分析", "", "持仓股详情|zh="+sourceDis+"|code="+stockCode+"|name="+stockName);
              })
            var _this = this;
            //收益分析切换
            $(".switch-more").on("click",function(){
                base.log(_this.swiper);
                base.log(_this.swiper.activeIndex);
                 if(_this.swiper.activeIndex){
                    //_this.swiper.slidePrev();
                    base.log("slidePrev");
                 }else{
                    _this.swiper.slideNext();
                    base.log("slideNext");
                 }                              
            });
        },
        //页面侦听的事件
        pageEvent: function() {
            $(window).scroll(function() {
                var top = $(window).scrollTop(),
                    bodyHeight = window.innerHeight,
                    totalHeight = $("body").height();
                    //alert(top);alert(bodyHeight);alert(totalHeight);
                if ((top + bodyHeight) >= totalHeight &&!dataEnd &&!isRefresh) {
                    isRefresh = true;
                    var time = setTimeout(function() {
                        page++;
                        income.getData();
                        clearTimeout(time);
                        time = null;
                    }, 300);
                }
            });
        }
    }
    income.init();
});